<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { MeetingEnrollVO } from '#/api/meeting/enroll/model';

import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

import { useAccess } from '@vben/access';
import { Page, useVbenModal } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
// import { VbenIcon } from '@vben/icons';
import { $t } from '@vben/locales';
import { getVxePopupContainer } from '@vben/utils';

import {
  Dropdown,
  Menu,
  MenuItem,
  Modal,
  Popconfirm,
  Space,
} from 'ant-design-vue';

import {
  useVbenVxeGrid,
  vxeCheckboxChecked,
  vxeCheckboxCheckedCount,
} from '#/adapter/vxe-table';
import {
  meetingEnrollAddFavoriteBySearch,
  // meetingEnrollExport,
  meetingEnrollChangeSignStatus,
  meetingEnrollDownloadImportTemplate,
  meetingEnrollImport,
  meetingEnrollInfo,
  meetingEnrollPage,
  meetingEnrollRemove,
} from '#/api/meeting/enroll';
import addEmployeeToFavoriteModal from '#/components/favorite/src/add-employee-modal.vue';
import importModal from '#/components/import/src/import-modal.vue';
import { DetailsModal } from '#/components/modal';
import { TableSwitch } from '#/components/table';
import { getDictOptions } from '#/utils/dict';

// import { commonDownloadExcel } from '#/utils/file/download';
import { columns, detailsSchema, querySchema } from './data';

const props = withDefaults(defineProps<Props>(), {
  extraColumns: () => [],
  readonly: false,
  meetingId: undefined,
  title: '',
});

// const emit = defineEmits<{ reload: [] }>();

interface Props {
  extraColumns?: any[];
  meetingId?: number | string;
  readonly?: boolean;
  title?: string;
}

const { hasAccessByCodes } = useAccess();
const searchData = ref<Record<string, any>>();
const total = ref(0);
const titleComp = computed(() => {
  const defaultTitle = '报名人员列表';
  return props.title
    ? `${props.title} - ${defaultTitle}`
    : `会议${defaultTitle}`;
});

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  fieldMappingTime: [
    [
      'createTime',
      ['createTimeStart', 'createTimeEnd'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
    [
      'auditTime',
      ['auditTimeStart', 'auditTimeEnd'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const pageData = {
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        };
        const queryData = {
          ...formValues,
        };

        if (props.meetingId) {
          queryData.meetingId = props.meetingId;
        }

        searchData.value = queryData;

        const resp = await meetingEnrollPage({ ...pageData, ...queryData });

        total.value = resp.total;

        return resp;
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  id: 'meeting-enroll-list-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

// 更新查询报名人员
watch(
  () => props.meetingId,
  async (id) => {
    if (id) {
      await tableApi?.reload();
    }
  },
);

const [MeetingEnrollDetailsModal, detailsModalApi] = useVbenModal({
  connectedComponent: DetailsModal,
});

const router = useRouter();

function handlePreview(record: MeetingEnrollVO) {
  detailsModalApi.setData(record);
  detailsModalApi.open();
}

function handleAudienceIdPreview(record: MeetingEnrollVO) {
  router.push(`/company/audience/details/${record.employeeId}`);
}

function handlePreviewCompany(record: MeetingEnrollVO) {
  router.push(`/company/manage/details/${record.companyId}`);
}

async function handleDelete(row: MeetingEnrollVO) {
  await meetingEnrollRemove(row.id);
  await tableApi.query();
}

// 导入
const [ImportModal, importModalApi] = useVbenModal({
  connectedComponent: importModal,
  destroyOnClose: true,
});

function handleImport() {
  importModalApi.setData({});
  importModalApi.open();
}

async function handleImportSuccess() {
  await tableApi.reload();
}

// 批量加入收藏夹
const [AddEmployeeToFavoriteModal, addEmployeeToFavoriteModalApi] =
  useVbenModal({
    connectedComponent: addEmployeeToFavoriteModal,
    destroyOnClose: true,
  });

function handleFavoriteMenuClick(e: any) {
  const type = e.key;
  if (type === 'check') {
    // 勾选加入
    const records = tableApi.grid.getCheckboxRecords();
    addEmployeeToFavoriteModalApi.setData({
      type,
      records,
      total: records.length,
    });
    addEmployeeToFavoriteModalApi.open();
  }
  if (type === 'search') {
    // 筛选加入
    addEmployeeToFavoriteModalApi.setData({
      type,
      searchData: searchData.value,
      total: total.value,
    });
    addEmployeeToFavoriteModalApi.open();
  }
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: MeetingEnrollVO) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await meetingEnrollRemove(ids);
      await tableApi.query();
    },
  });
}

// function handleDownloadExcel() {
//   commonDownloadExcel(
//     registerExport,
//     '个人登记数据',
//     tableApi.formApi.form.values,
//     {
//       fieldMappingTime: formOptions.fieldMappingTime,
//     },
//   );
// }

async function reload() {
  await tableApi.reload();
}

async function statusUpdate(row: MeetingEnrollVO) {
  const data = {
    id: row.id,
    signStatus: row.signStatus,
  };
  await meetingEnrollChangeSignStatus(data);
}

defineExpose({
  reload,
});

onMounted(() => {
  const exhibitionNumberList = getDictOptions(DictEnum.EXHIBITION_NUMBER, true);
  console.log(exhibitionNumberList.length);
  if (exhibitionNumberList?.length > 0) {
    console.log(exhibitionNumberList[0]);
    tableApi.formApi.updateSchema([
      { fieldName: 'number', defaultValue: exhibitionNumberList[0]?.dictValue },
    ]);
  }
});
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable>
      <template #table-title>
        <main-title :text="titleComp" />
      </template>
      <template #toolbar-tools>
        <Space>
          <a-button
            v-if="!readonly && hasAccessByCodes(['meeting:enroll:import'])"
            @click="handleImport"
          >
            导入
          </a-button>
          <!--<a-button-->
          <!--  v-access:code="['register:sourceTrack:export']"-->
          <!--  @click="handleDownloadExcel"-->
          <!--&gt;-->
          <!--  导出-->
          <!--</a-button>-->
          <Dropdown>
            <template #overlay>
              <Menu @click="handleFavoriteMenuClick">
                <span v-access:code="['employee:favorite:addMember']">
                  <MenuItem
                    key="check"
                    :disabled="!vxeCheckboxChecked(tableApi)"
                  >
                    按勾选加入({{ vxeCheckboxCheckedCount(tableApi) }})
                  </MenuItem>
                </span>
                <span v-access:code="['meeting:enroll:addFavoriteBySearch']">
                  <MenuItem key="search" :disabled="total === 0">
                    按当前搜索结果加入({{ total }})
                  </MenuItem>
                </span>
              </Menu>
            </template>
            <a-button
              v-access:code="[
                'employee:favorite:addMember',
                'meeting:enroll:addFavoriteBySearch',
              ]"
            >
              批量加入收藏夹
            </a-button>
          </Dropdown>
          <a-button
            v-if="hasAccessByCodes(['meeting:enroll:remove'])"
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            @click="handleMultiDelete"
          >
            {{ $t('pages.common.delete') }}
          </a-button>
        </Space>
      </template>
      <template #name="{ row }">
        <a-button
          v-if="row.employeeId && hasAccessByCodes(['employee:manager:query'])"
          type="link"
          class="pr-[5px]"
          @click="handleAudienceIdPreview(row)"
        >
          {{ row.name }}
        </a-button>
        <span v-else class="mr-[5px]">{{ row.name }}</span>
      </template>
      <template #signStatus="{ row }">
        <TableSwitch
          v-model:value="row.signStatus"
          :checked-value="1"
          checked-text=""
          :un-checked-value="0"
          un-checked-text=""
          :api="() => statusUpdate(row)"
          :disabled="!hasAccessByCodes(['meeting:enroll:changeSignStatus'])"
          @reload="tableApi.query()"
        />
      </template>
      <template #companyName="{ row }">
        <a-button
          v-if="row.companyId && hasAccessByCodes(['company:manager:query'])"
          type="link"
          @click="handlePreviewCompany(row)"
        >
          {{ row.companyName }}
        </a-button>
        <div v-else>{{ row.companyName }}</div>
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['meeting:enroll:query']"
            @click.stop="handlePreview(row)"
          >
            {{ $t('pages.common.info') }}
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              v-if="hasAccessByCodes(['meeting:enroll:remove'])"
              danger
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
          <slot name="action" v-bind="{ row }"></slot>
        </Space>
      </template>
    </BasicTable>
    <ImportModal
      :import-api="meetingEnrollImport"
      :download-api="meetingEnrollDownloadImportTemplate"
      @reload="handleImportSuccess"
    />
    <MeetingEnrollDetailsModal
      :columns="detailsSchema()"
      :api="meetingEnrollInfo"
    />
    <AddEmployeeToFavoriteModal
      id-key="employeeId"
      :add-by-search-api="meetingEnrollAddFavoriteBySearch"
      @reload="tableApi.reload()"
    />
  </Page>
</template>
